<template>
  <div class="content-wrapper" v-loading="loading">
    <div class="body">
      <el-row :gutter="24" style="height:100%">
        <el-col :span="11" class="left">
          <div class="panel">
            <el-card>
              <el-divider content-position="left"
                ><h3>已有组成员</h3></el-divider
              >
              <el-form
                style="width:400px;"
                label-position="top"
                label-width="80px"
                :model="formData"
                ref="memberForm"
              >
                <el-form-item prop="samAccountName">
                  <el-button
                    @click="
                      importDialogVisible = true;
                      importStep = 0;
                    "
                  >
                    批量导入</el-button
                  >
                  <el-button @click="getMembers"> 刷新</el-button>
                </el-form-item>
              </el-form>
              <el-table
                class="dense-table"
                :data="groupMembers.list"
                empty-text="请选择组成员"
              >
                <el-table-column
                  label="员工编号"
                  align="left"
                  key="description"
                  prop="description"
                >
                  <template scope="scope">
                    <svg-icon
                      :icon-class="getIcon(scope.row)"
                      style="margin-right:5px"
                    />{{ scope.row.description }}
                  </template>
                </el-table-column>

                <el-table-column
                  label="中文姓名"
                  align="left"
                  key="displayName"
                  prop="displayName"
                />
                <el-table-column
                  label="英文名"
                  align="left"
                  key="name"
                  prop="name"
                />

                <el-table-column
                  label="职务"
                  align="left"
                  key="title"
                  prop="title"
                  :show-overflow-tooltip="true"
                />

                <el-table-column
                  label="邮箱"
                  align="left"
                  key="mail"
                  prop="mail"
                />
                <el-table-column
                  label="职务"
                  align="left"
                  key="department"
                  prop="department"
                />
                <el-table-column
                  label="操作"
                  align="center"
                  width="50px"
                  fixed="right"
                >
                  <template scope="scope">
                    <el-button
                      type="text"
                      @click="handleRemoveGroupMember(scope.row)"
                      >删除</el-button
                    >
                  </template></el-table-column
                >
              </el-table>
              <pagination
                v-show="groupMembers.page.total > 0"
                :total="groupMembers.page.total"
                :page.sync="groupMembers.page.pageNum"
                :limit.sync="groupMembers.page.pageSize"
                @pagination="getMembers"
              />
            </el-card>
          </div>
        </el-col>
        <el-col :span="12" class="right">
          <div class="panel">
            <el-card>
              <div class="form-wrapper">
                <el-divider content-position="left"
                  ><h3>添加组成员</h3></el-divider
                >
                <el-form
                  style="width:400px;"
                  label-position="top"
                  label-width="80px"
                  :model="formData"
                  ref="memberForm"
                >
                  <el-form-item prop="samAccountName">
                    <el-button @click="pickPersonDialogVisible = true">
                      选择组成员</el-button
                    >

                    <el-button
                      @click="
                        personList = personList.filter(
                          n => !personListSelected.includes(n.samAccountName)
                        )
                      "
                    >
                      删除</el-button
                    >
                  </el-form-item>
                </el-form>
                <el-table
                  class="dense-table"
                  :data="personList"
                  empty-text="请选择组成员"
                  @selection-change="handleSelectPersonChange"
                >
                  <el-table-column type="selection" width="50" align="center" />

                  <el-table-column
                    label="员工编号"
                    align="left"
                    key="description"
                    prop="description"
                  >
                    <template scope="scope">
                      <svg-icon
                        :icon-class="getIcon(scope.row)"
                        style="margin-right:5px"
                      />{{ scope.row.description }}
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="中文姓名"
                    align="left"
                    key="displayName"
                    prop="displayName"
                  />
                  <el-table-column
                    label="英文名"
                    align="left"
                    key="name"
                    prop="name"
                  />

                  <el-table-column
                    label="职务"
                    align="left"
                    key="title"
                    prop="title"
                    :show-overflow-tooltip="true"
                  />

                  <el-table-column
                    label="邮箱"
                    align="left"
                    key="mail"
                    prop="mail"
                  />
                  <el-table-column
                    label="职务"
                    align="left"
                    key="department"
                    prop="department"
                  />
                  <el-table-column
                    label="操作"
                    align="center"
                    width="50px"
                    fixed="right"
                  >
                    <template scope="scope">
                      <el-button
                        type="text"
                        @click="
                          personList = personList.filter(
                            n => n.samAccountName != scope.row.samAccountName
                          )
                        "
                        >删除</el-button
                      >
                    </template></el-table-column
                  >
                </el-table>
                <div style="text-align:center;padding:10px">
                  <el-button class="btn" type="primary" @click="submitForm()"
                    >保存修改</el-button
                  >
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 添加组成员弹窗 -->
    <el-dialog
      width="750px"
      :visible.sync="pickPersonDialogVisible"
      title="选择组成员"
      custom-class="pickPersonDialog"
    >
      <el-tabs type="border-card" style="min-height:300px;margin-bottom:10px;">
        <el-tab-pane label="按组织架构">
          <el-tree
            class="tree-line"
            :indent="0"
            :data="ouTree"
            :expand-on-click-node="false"
            ref="tree"
            node-key="id"
            lazy
            :props="treeProps"
            :load="getSubTree"
            highlight-current
            @current-change="queryGroupMemberByOU"
        /></el-tab-pane>
        <el-tab-pane label="组合查询">
          <el-form label-width="100px" v-model="queryForm">
            <el-form-item label="账号">
              <el-input
                placeholder="账号"
                v-model="queryForm.account"
              ></el-input>
            </el-form-item>
            <el-form-item label="部门">
              <el-input
                placeholder="部门"
                v-model="queryForm.department"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input placeholder="邮箱" v-model="queryForm.mail"></el-input>
            </el-form-item>
            <div style="text-align:center">
              <el-button type="primary" @click="queryGroupMemberByCondition()"
                >查询</el-button
              >
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <el-row :gutter="24" style=" height: 300px;">
        <!-- <el-transfer
          style="display: flex;justify-content: center;align-items: center;"
          v-model="personToSave"
          :data="personDataSource"
          :titles="['搜索人员', '待保存人员']"
        ></el-transfer> -->
        <el-col :span="11" style="height:100%">
          <el-card class="box-card" style="height:100%;overflow:auto;">
            <div slot="header" class="clearfix">
              <span>选择组成员</span>
            </div>
            <el-checkbox-group v-model="personDataSourceCheckList">
              <div
                v-for="person in personDataSource"
                :key="person.samAccountName"
                class="text item"
              >
                <el-checkbox :label="person.samAccountName">
                  <template
                    ><svg-icon
                      :icon-class="getIcon(person)"
                      style="margin-right:5px"
                    />{{ person.samAccountName }}</template
                  >
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-card>
        </el-col>
        <el-col
          style="display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;"
          :span="2"
          ><el-button
            type="primary"
            circle
            size="mini"
            icon="el-icon-arrow-right"
            @click="toSave()"
          ></el-button>
          <el-button
            type="primary"
            circle
            size="mini"
            icon="el-icon-arrow-left"
            @click="toDataSource()"
          ></el-button>
        </el-col>
        <el-col :span="11" style="height:100%;">
          <el-card class="box-card" style="height:100%;overflow:auto;">
            <div slot="header" class="clearfix">
              <span>保存组成员</span>
            </div>
            <el-checkbox-group v-model="personToSaveCheckList">
              <div
                v-for="person in personToSave"
                :key="person.distinguishedName"
                class="text item"
              >
                <el-checkbox :label="person.samAccountName">
                  <template
                    ><svg-icon
                      :icon-class="getIcon(person)"
                      style="margin-right:5px"
                    />{{ person.samAccountName }}</template
                  >
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPickPerson">取 消</el-button>
        <el-button
          type="primary"
          @click="
            personList = personList.concat(
              personToSave.filter(
                n => !personList.find(r => n.samAccountName == r.samAccountName)
              )
            );
            resetPickPerson();
          "
          >确定</el-button
        >
      </span>
    </el-dialog>
    <!-- <el-dialog
      width="600px"
      :visible.sync="importDialogVisible"
      title="批量导入人员"
    >
      <el-form label-width="200px" v-model="importForm">
        <el-form-item label="导入方式" key="importType" prop="importType">
          <el-radio v-model="importForm.importType" label="upload"
            >上传EXCEL
          </el-radio>

          <el-radio v-model="importForm.importType" label="clipboard"
            >粘贴文本</el-radio
          >
        </el-form-item>
        <div
          style="padding:5px 20px;"
          v-if="importForm.importType == 'clipboard'"
        >
          <el-alert
            title="文本格式"
            type="info"
            description="用户账号 多个用户账号之间用回车换行"
            show-icon
          >
          </el-alert>

          <el-input
            type="textarea"
            :rows="10"
            placeholder="zhangsan1
zhangsan2
zhangsan3"
            v-model="importForm.clipboardText"
          >
          </el-input>
        </div>
      </el-form>

      <el-upload
        v-if="importForm.importType == 'upload'"
        style="text-align:center"
        class="upload-file"
        drag
        action="https://jsonplaceholder.typicode.com/posts/"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div
          class="el-upload__tip"
          slot="tip"
          style="display: flex;justify-content: center;align-items: center;"
        >
          请按<el-link type="primary">模板</el-link>填写数据后，上传Excel文件
        </div>
      </el-upload>

      <div style="text-align:center;margin-top:20px;">
        <el-button type="primary" @click="handleImport()">开始导入</el-button>
      </div>
    </el-dialog> -->
    <el-dialog
      width="600px"
      :visible.sync="importDialogVisible"
      title="批量导入人员"
    >
      <div style="width:400px;margin:0 auto">
        <el-steps :active="importStep" simple>
          <el-step title="导入数据" icon="el-icon-edit"></el-step>
          <el-step title="查看结果" icon="el-icon-upload"></el-step>
        </el-steps>
      </div>
      <template v-if="importStep == 0">
        <el-form label-width="200px" v-model="importForm">
          <el-form-item label="导入方式" key="importType" prop="importType">
            <el-radio v-model="importForm.importType" label="upload"
              >上传EXCEL
            </el-radio>

            <el-radio v-model="importForm.importType" label="clipboard"
              >粘贴文本</el-radio
            >
          </el-form-item>
          <div
            style="padding:5px 20px;"
            v-if="importForm.importType == 'clipboard'"
          >
            <el-alert
              title="文本格式"
              type="info"
              description="用户账号 多个用户账号之间用回车换行"
              show-icon
            >
            </el-alert>

            <el-input
              type="textarea"
              :rows="10"
              placeholder="zhangsan1
zhangsan2
zhangsan3"
              v-model="importForm.clipboardText"
            >
            </el-input>
          </div>
        </el-form>
        <el-upload
          v-if="importForm.importType == 'upload'"
          style="text-align:center"
          class="upload-file"
          drag
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
          :before-upload="beforeUpload"
          :limit="1"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传xls/xlsx文件，且不超过10M
          </div>
          <div
            class="el-upload__tip"
            slot="tip"
            style="display: flex;justify-content: center;align-items: center;"
          >
            请按<el-link
              :href="`${env.VUE_APP_BASE_API}/ad/group/downloadGroupTemplate`"
              type="primary"
              >模板</el-link
            >填写数据后，上传Excel文件
          </div>
        </el-upload>
        <div style="text-align:center;margin-top:20px;">
          <el-button
            v-if="importForm.importType == 'upload'"
            type="primary"
            @click="submitUpload()"
            >开始导入</el-button
          >
          <el-button
            v-if="importForm.importType == 'clipboard'"
            type="primary"
            @click="confirmImport()"
            >开始导入</el-button
          >
        </div>
      </template>
      <div v-if="importStep == 1" style="padding-top: 10px;">
        <el-table
          :data="ImportStateList"
          size="mini"
          style="width: 100%"
          height="250"
        >
          <el-table-column
            label="账号"
            align="left"
            key="samAccountName"
            prop="samAccountName"
          />
          <el-table-column
            label="导入状态"
            align="left"
            key="importState"
            prop="importState"
          />
          <el-table-column
            label="错误详情"
            align="left"
            key="errorMsg"
            prop="errorMsg"
          />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import groupApi from "@/api/activeDirectory/group";
import personApi from "@/api/activeDirectory/person";
import { orgMixin } from "../mixin/org";

export default {
  name: "groupMember",
  mixins: [orgMixin],
  data() {
    // wait / process / finish / error / success
    return {
      formNames: ["basicForm", "memberForm"],
      formData: {
        samAccountName: "",
        scope: "Global",
        groupTypePart: "SecurityGroup",
        groupType: "",
        member: [],
        orgDN: "",
        //上传返回的数据
        ImportStateList: null
      },
      importTextValue: {
        text: "",
        distinguishedName: ""
      },
      loading: false,

      //选择人员弹窗
      pickPersonDialogVisible: false,

      personDataSource: [],
      personDataSourceCheckList: [],
      personToSave: [],
      personToSaveCheckList: [],

      //组成员列表
      groupMembers: { list: [], page: { total: 0, pageNum: 1, pageSize: 10 } },

      //添加后的人员列表
      personList: [],

      personListSelected: [],
      // 查询参数
      personQuery: {
        samAccountName: undefined,
        orgDN: undefined
      },
      queryForm: { account: undefined, mail: undefined, department: undefined },
      importDialogVisible: false,
      importStep: 0,
      importForm: {
        importType: "upload", //导入数据方式 upload 或 clipboard

        clipboardText: ""
      }
    };
  },
  created() {
    this.formData.distinguishedName = this.$route.params.distinguishedName;
    this.formData.groupType = this.groupType;
  },
  mounted() {
    this.getMembers();
  },
  props: {},
  methods: {
    //#region 分部表单
    async getMembers() {
      this.loading = true;
      const res2 = await groupApi.membersPage(
        this.formData.distinguishedName,
        this.groupMembers.page
      );
      if (res2.success) {
        this.groupMembers.list = res2.data.data;
        this.groupMembers.page.total = res2.data.pagination.dataCount;
      }
      this.loading = false;
    },

    //分部表单校验
    validateForm() {
      let res = false;
      this.$refs[this.currentForm].validate(valid => {
        res = valid;
        return valid;
      });
      return res;
    },

    //提交
    async submitForm() {
      if (this.personList.length == 0) {
        this.$message.warning("至少添加一位组成员");
        return;
      }
      this.loading = true;
      const res = await groupApi
        .addGroupMember(this.formData.distinguishedName, {
          members: this.personList.map(n => n.distinguishedName)
        })
        .catch(n => {})
        .finally(() => {
          this.loading = false;
        });
      if (res.success) {
        this.$message.success("保存成功");
        this.getMembers();
        this.personList = [];
      }
    },

    handleSelectPersonChange(selection) {
      this.personListSelected = selection.map(n => n.samAccountName);
    },
    handleRemoveGroupMember(row) {
      this.$confirm(
        "是否确认删除组成员【" + row.samAccountName + "】?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          return groupApi.removeGroupMember(this.formData.distinguishedName, {
            members: [row.distinguishedName]
          });
        })
        .then(res => {
          if (res.success) {
            this.getMembers();
            this.msgSuccess("删除成功");
          }
        });
    },

    getIcon(row) {
      return row.objectCategory.includes("Group") ? "ad-group" : "ad-person";
    },
    //#endregion

    //#region 弹窗相关

    // OU树单击事件 搜索人员
    queryGroupMemberByOU(node) {
      this.personQuery.samAccountName = node.data.samAccountName;
      this.personQuery.orgDN = node.data.distinguishedName;
      this.loading = true;
      groupApi
        .members(this.personQuery)
        .then(res => {
          this.personDataSource = res.data;
          this.personDataSourceCheckList = [];

          // this.personDataSource = res.data.data.map(n => ({
          //   key: n.distinguishedName,
          //   label: n.samAccountName
          // }));
        })
        .catch()
        .finally(n => {
          this.loading = false;
        });
    },
    queryGroupMemberByCondition() {
      const { account, mail, department } = this.queryForm;
      if (!account && !mail && !department) {
        this.$message.warning("查询条件不能同时为空！");
        return;
      }
      this.loading = true;
      groupApi
        .searchMembers(this.queryForm)
        .then(res => {
          this.personDataSource = res.data;
          this.personDataSourceCheckList = [];

          // this.personDataSource = res.data.data.map(n => ({
          //   key: n.distinguishedName,
          //   label: n.samAccountName
          // }));
        })
        .catch()
        .finally(n => {
          this.loading = false;
        });
    },
    // 上传excel
    beforeUpload(file) {
      this.files = file;
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt5M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message.warning("上传模板只能是 xls、xlsx格式!");
        return;
      }
      if (!isLt5M) {
        this.$message.warning("上传模板大小不能超过 10MB!");
        return;
      }
      this.fileName = file.name;
      return true; // 返回false不会自动上传
    },
    // 上传excel
    submitUpload() {
      if (!this.files) {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }
      let fileFormData = new FormData();
      fileFormData.append("distinguishedName", this.formData.distinguishedName);
      //filename是键，file是值，就是要传的文件，test是要传的文件名
      fileFormData.append("files", this.files, this.fileName);

      let requestConfig = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      // 执行上传excel
      groupApi
        .importExcel(fileFormData)
        .then(resp => {
          if (resp.success) {
            this.importDialogVisible = false;
            this.getMembers();
          } else {
            this.importStep = 1;
            this.ImportStateList = resp.data;
          }
        })
        .catch(e => {
          console.log(e);
          // this.$message.error("excel上传失败，请重新上传");
        });
    },
    async confirmImport() {
      const { importType } = this.importForm;
      if (importType == "upload") {
      } else if (importType == "clipboard") {
        if (!this.importForm.clipboardText) {
          this.$message.warning("请粘贴文本！");
          return;
        }
        this.importTextValue.text = this.importForm.clipboardText;
        this.importTextValue.distinguishedName = this.formData.distinguishedName;
        const res = await groupApi.importMemberFromClipboard({
          text: this.importForm.clipboardText,
          distinguishedName: this.formData.distinguishedName
        });
        if (res.success) {
          this.importDialogVisible = false;
          this.getMembers();
        } else {
          this.importStep = 1;
          this.ImportStateList = res.data;
        }
      }
    },
    //
    toSave() {
      this.personToSave = this.personToSave.concat(
        this.personDataSource.filter(
          n =>
            this.personDataSourceCheckList.includes(n.samAccountName) &&
            !this.personToSave.find(r => r.samAccountName == n.samAccountName)
        )
      );
      this.personToSaveCheckList = this.personToSaveCheckList.concat(
        this.personDataSourceCheckList
      );
      this.personDataSource = this.personDataSource.filter(
        n =>
          !this.personDataSourceCheckList.includes(n.samAccountName) &&
          !this.personToSave.find(r => r.samAccountName == n.samAccountName)
      );
      this.personDataSourceCheckList = [];
    },
    //
    toDataSource() {
      this.personDataSource = this.personDataSource.concat(
        this.personToSave.filter(
          n =>
            this.personToSaveCheckList.includes(n.samAccountName) &&
            !this.personDataSource.find(
              r => r.samAccountName == n.samAccountName
            )
        )
      );
      this.personDataSourceCheckList = this.personDataSourceCheckList.concat(
        this.personToSaveCheckList
      );
      this.personToSave = this.personToSave.filter(
        n =>
          !this.personToSaveCheckList.includes(n.samAccountName) &&
          !this.personDataSource.find(r => r.samAccountName == n.samAccountName)
      );
      this.personToSaveCheckList = [];
    },
    resetPickPerson() {
      this.pickPersonDialogVisible = false;
      this.personDataSource = [];
      this.personDataSourceCheckList = [];
      this.personToSave = [];
      this.personToSaveCheckList = [];
    },
    resetImportForm() {
      this.importForm.clipboardText = "";
    }

    //#endregion
  },
  computed: {
    prevStepEnable() {
      return this.activeStep > 0;
    },
    nextStepEnable() {
      return this.activeStep < this.steps.length;
    },
    groupType() {
      return this.formData.scope + this.formData.groupTypePart;
    },
    currentForm() {
      return this.formNames[this.activeStep];
    },
    isLastStep() {
      return this.activeStep == this.steps.length - 2;
    },
    env() {
      return process.env;
    }
  },
  watch: {
    groupType(val) {
      this.formData.groupType = val;
    },
    pickPersonDialogVisible(val) {
      if (val) {
        this.getTreeselect();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.content-wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .body {
    overflow-y: auto;

    position: relative;
    width: 100%;
    height: 100%;
    .left {
      border-right: 1px solid rgb(232, 232, 232);
    }
    .left,
    .right {
      height: 100%;
      .panel {
        height: 100%;
        padding: 20px 20px;
        .el-card {
          height: 100%;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.pickPersonDialog {
  .el-tabs__content {
    max-height: 250px;
    overflow: auto;
  }
  .el-dialog__body {
    padding: 0 20px;
  }
  .tree-line {
    .el-tree-node {
      position: relative;
      padding-left: 16px; // 缩进量
    }
    .el-tree-node__children {
      padding-left: 16px; // 缩进量
    }

    // 竖线
    .el-tree-node::before {
      content: "";
      height: 100%;
      width: 1px;
      position: absolute;
      left: -3px;
      top: -26px;
      border-width: 1px;
      border-left: 1px dashed #52627c;
    }
    // 当前层最后一个节点的竖线高度固定
    .el-tree-node:last-child::before {
      height: 38px; // 可以自己调节到合适数值
    }

    // 横线
    .el-tree-node::after {
      content: "";
      width: 24px;
      height: 20px;
      position: absolute;
      left: -3px;
      top: 12px;
      border-width: 1px;
      border-top: 1px dashed #52627c;
    }

    // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
    & > .el-tree-node::after {
      border-top: none;
    }
    & > .el-tree-node::before {
      border-left: none;
    }

    // 展开关闭的icon
    .el-tree-node__expand-icon {
      font-size: 16px;
      // 叶子节点（无子节点）
      &.is-leaf {
        color: transparent;
        // display: none; // 也可以去掉
      }
    }
  }
}
</style>
